import {CSSProperties, memo, useEffect} from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Link, useParams } from 'react-router-dom';
import { Avatar, Button, message, Popconfirm, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { API_BASEURL } from '@/constants/api';
import { resAddOrCancelFollow, resFollow } from '@/services/follow';
import { userStore } from '@/store/userStore';
import { useAntdTable } from 'ahooks';
import { useRecoilValue } from 'recoil';
import ProfileContainer from '@/components/ProfileContainer';
import { formatTime } from '@/utils/format';

const createColumns = (refresh: () => void): ColumnsType<API.FollowStruct> => {
  return [
    {
      title: <div className={'font-bold'}>用户名称</div>,
      align: 'center',
      render: (_, follow) => {
        return (
          <div className={'flex-justify-items-center'}>
            <Avatar src={API_BASEURL + '/' + follow?.follower?.avatar} />
            <Link to={`/user_page/` + follow?.followers_id} className={'ml-2'}>
              {follow.follower?.name}
            </Link>
          </div>
        );
      },
    },
    {
      title: <div className={'font-bold'}>关注时间</div>,
      dataIndex: 'created_at',
      align: 'center',
      render: (create_at) => <div>{formatTime(create_at)}</div>,
    },
    {
      title: <div className={'font-bold'}>操作</div>,
      align: 'center',
      render: (_, follow) => (
        <Popconfirm
          title={'您确定要取消此关注吗'}
          cancelText="取消"
          okText="确定"
          onConfirm={() => {
            resAddOrCancelFollow(follow.followers_id).then(() => {
              message.success('取消关注成功！');
              refresh();
            });
          }}
        >
          <Button type={'link'}>取消关注</Button>
        </Popconfirm>
      ),
    },
  ];
};

const FollowPage: FC<
  PropsWithChildren<{ style?: CSSProperties; showTitle?: boolean;refreshCount?:number }>
> = ({ style, showTitle = true ,refreshCount}) => {
  const user = useRecoilValue(userStore);
  const params = useParams();
  const id = Number(params.id) || user.id;
  const { tableProps, pagination } = useAntdTable(({ pageSize, current }) => {
    return resFollow(id, {
      pageSize,
      current,
    });
  },{ cacheKey: 'useFollowCache' });

  const refresh = () => {
    pagination.changeCurrent(pagination.current);
  }

  useEffect(() => {
    refresh()
  },[refreshCount])

  const columns = createColumns(refresh);

  return showTitle ? (
    <ProfileContainer title={'我的关注'} style={style}>
      <Table columns={columns} rowKey="id" {...tableProps} />
    </ProfileContainer>
  ) : (
    <Table columns={columns} rowKey="id" {...tableProps} />
  );
};

export default memo(FollowPage);
